import os
import numpy as np
from transfer import trans_matrix, matrix_translation, convert_digit, objectes, check_hole_
from dect import det_hole, weights_hole
from infer_format import ModelResult
import time
import logging

logging.basicConfig(format='%(asctime)s.%(msecs)03d [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s',
                    datefmt='## %Y-%m-%d %H:%M:%S')
logging.getLogger().setLevel(logging.DEBUG)
logger = logging.getLogger()


def do_check(img: np.ndarray, model_obj, labels_):
    st = time.time()
    res = ModelResult()
    res.add_custom_data("model_name", "cv_plate_hole_model")
    try:
        st_model = time.time()
        plate_holes = det_hole(img, model_obj, labels_)
        print("   ------- 孔洞数量 ---------  ", len(plate_holes))
        # 未检测到 默认替代
        if len(plate_holes) > 2:
            plate_holes = check_hole_(plate_holes)
            hole_num, hole_check_num, hole_status = convert_digit(matrix_translation(trans_matrix(plate_holes)))
        else:
            hole_num, hole_check_num, hole_status = "999999", "9", False
        logger.info(f'孔洞初次识别结果：{hole_num, hole_check_num, hole_status}')
        time_hole = int((time.time() - st_model) * 1000)
        # 记录所有识别点位
        res.object.extend(objectes(plate_holes))
        # 添加业务自定义结构
        # no 最后识别的编号
        # hole {"status":False,"sample_type":"P","no":"123123","check_no":"A"},
        # no  {"status":False,"sample_type":"P","no":"123123","check_no":"A"}
        # 公式转换校验数字 = 孔洞输出校验数字,孔牌识别正确
        if hole_status:
            res.add_custom_data("model_hole",
                                {"status": True, "sample_type": "P", "no": hole_num, "check_no": hole_check_num,
                                 "time": time_hole})
        else:
            res.add_custom_data("model_hole",
                                {"status": False, "sample_type": "N", "no": hole_num, "check_no": hole_check_num,
                                 "time": time_hole})

            # print("   ------- 孔洞数量 ---------  ", len(plate_holes))
            # for iii in range(len(plate_holes)):
            #     print("        ", plate_holes[iii])

        res.add_custom_data("no", "999999")
        res.add_custom_data("check_no", "9")
    except Exception as e:
        # 捕获所有异常并执行相应操作
        logger.error(f'An error occurred:, {e}')
        res.add_custom_data("error", str(e))
        # 均识别错误返回默认占位
        res.add_custom_data("model_hole",
                            {"status": False, "sample_type": "N", "no": "999999", "check_no": "9", "time": 0})
    res.set_time(time.time() - st)
    # logger.info(f'时间：{res.time}毫秒')
    return res

